﻿using PureMVC.Interfaces;
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace PureMVC.Patterns
{
    public class Observer : IObserver
    {
        private object m_notifyContext; //对应的那种类
        private string m_notifyMethod; //对应的方法
        protected readonly object m_syncRoot=new object();
        public Observer(string notifyMethod,object notifyContext)
        {
            this.m_notifyContext = notifyContext;
            this.m_notifyMethod = notifyMethod;
        }
        public object NotifyContext
        {
            private get
            {
                return this.m_notifyContext;
            }
            set
            {
                this.m_notifyContext=value;
            }
        }

        public string NotifyMethod
        {
            private get
            {
                return this.m_notifyMethod;
            }
            set
            {
                this.m_notifyMethod=value;
            }
        }

        public bool CompareNotifyContext(object obj)
        {
            lock(this.m_syncRoot)
            {
                return this.NotifyContext.Equals(obj);
            }
        }

        public void NotifyObserver(INotification notification)
        {
            object notifyContext;
            lock(this.m_syncRoot)
            {
                notifyContext = this.NotifyContext;
            }
            //利用反射获取方法然后执行
            Type type=notifyContext.GetType();
            //这里设置忽略字母的大小写
            BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase ;

            MethodInfo method = type.GetMethod(this.NotifyMethod, bindingAttr);
            method.Invoke(notifyContext, new object[] { notification });
        }
    }
}

